package com.datagateway.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;

/**
 * 数据校验规则引擎
 * 负责实现可配置的数据校验规则，包括字段校验、格式校验、业务规则校验等
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@Component
public class DataValidationEngine {

    private static final Logger logger = LoggerFactory.getLogger(DataValidationEngine.class);

    @Autowired
    private AlertManager alertManager;

    /**
     * 校验统计
     */
    private final AtomicLong totalValidations = new AtomicLong(0);
    private final AtomicLong totalSuccessfulValidations = new AtomicLong(0);
    private final AtomicLong totalFailedValidations = new AtomicLong(0);
    private final AtomicLong totalRuleViolations = new AtomicLong(0);

    /**
     * 校验配置
     */
    private boolean validationEnabled = true;
    private boolean strictMode = false;
    private boolean stopOnFirstError = false;
    private int maxValidationDepth = 10;
    private long validationTimeout = 5000; // 5秒

    /**
     * 校验规则存储
     */
    private final Map<String, ValidationRule> validationRules = new ConcurrentHashMap<>();
    private final Map<String, ValidationRuleSet> validationRuleSets = new ConcurrentHashMap<>();
    private final Map<String, ValidationConfig> validationConfigs = new ConcurrentHashMap<>();

    /**
     * 对象映射器
     */
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 初始化数据校验规则引擎
     */
    public void initialize() {
        try {
            // 注册默认校验规则
            registerDefaultValidationRules();
            
            // 创建默认校验规则集
            createDefaultValidationRuleSets();
            
            logger.info("数据校验规则引擎初始化成功");
            
        } catch (Exception e) {
            logger.error("数据校验规则引擎初始化失败", e);
            alertManager.sendSystemErrorAlert("数据校验规则引擎初始化失败", e.getMessage());
        }
    }

    /**
     * 校验数据
     * 
     * @param data 数据
     * @param ruleSetName 规则集名称
     * @return 校验结果
     */
    public ValidationResult validate(String data, String ruleSetName) {
        if (!validationEnabled) {
            return new ValidationResult(true, "VALIDATION_DISABLED", "数据校验已禁用", new ArrayList<>());
        }

        try {
            totalValidations.incrementAndGet();
            
            ValidationRuleSet ruleSet = validationRuleSets.get(ruleSetName);
            if (ruleSet == null) {
                totalFailedValidations.incrementAndGet();
                return new ValidationResult(false, "RULE_SET_NOT_FOUND", 
                    "未找到校验规则集: " + ruleSetName, new ArrayList<>());
            }
            
            // 解析数据
            Object parsedData = parseData(data);
            
            // 执行校验
            List<ValidationError> errors = new ArrayList<>();
            boolean isValid = executeValidation(parsedData, ruleSet, errors, 0);
            
            if (isValid) {
                totalSuccessfulValidations.incrementAndGet();
                return new ValidationResult(true, "VALID", "数据校验通过", errors);
            } else {
                totalFailedValidations.incrementAndGet();
                totalRuleViolations.addAndGet(errors.size());
                return new ValidationResult(false, "INVALID", "数据校验失败", errors);
            }
            
        } catch (Exception e) {
            totalFailedValidations.incrementAndGet();
            logger.error("数据校验异常: {}", ruleSetName, e);
            return new ValidationResult(false, "VALIDATION_ERROR", e.getMessage(), new ArrayList<>());
        }
    }

    /**
     * 校验数据（使用默认规则集）
     * 
     * @param data 数据
     * @return 校验结果
     */
    public ValidationResult validate(String data) {
        return validate(data, "default");
    }

    /**
     * 批量校验数据
     * 
     * @param dataList 数据列表
     * @param ruleSetName 规则集名称
     * @return 校验结果列表
     */
    public List<ValidationResult> batchValidate(List<String> dataList, String ruleSetName) {
        List<ValidationResult> results = new ArrayList<>();
        
        for (String data : dataList) {
            results.add(validate(data, ruleSetName));
        }
        
        return results;
    }

    /**
     * 创建校验规则
     * 
     * @param ruleName 规则名称
     * @param ruleType 规则类型
     * @param fieldPath 字段路径
     * @param ruleConfig 规则配置
     * @return 是否创建成功
     */
    public boolean createValidationRule(String ruleName, String ruleType, String fieldPath, Map<String, Object> ruleConfig) {
        try {
            ValidationRule rule = new ValidationRule(ruleName, ruleType, fieldPath, ruleConfig);
            validationRules.put(ruleName, rule);
            
            logger.info("校验规则创建成功: {} (类型: {}, 字段: {})", ruleName, ruleType, fieldPath);
            return true;
            
        } catch (Exception e) {
            logger.error("创建校验规则失败: {}", ruleName, e);
            return false;
        }
    }

    /**
     * 创建校验规则集
     * 
     * @param ruleSetName 规则集名称
     * @param ruleNames 规则名称列表
     * @param description 描述
     * @return 是否创建成功
     */
    public boolean createValidationRuleSet(String ruleSetName, List<String> ruleNames, String description) {
        try {
            List<ValidationRule> rules = new ArrayList<>();
            for (String ruleName : ruleNames) {
                ValidationRule rule = validationRules.get(ruleName);
                if (rule != null) {
                    rules.add(rule);
                } else {
                    logger.warn("校验规则不存在: {}", ruleName);
                }
            }
            
            ValidationRuleSet ruleSet = new ValidationRuleSet(ruleSetName, rules, description);
            validationRuleSets.put(ruleSetName, ruleSet);
            
            logger.info("校验规则集创建成功: {} (规则数量: {})", ruleSetName, rules.size());
            return true;
            
        } catch (Exception e) {
            logger.error("创建校验规则集失败: {}", ruleSetName, e);
            return false;
        }
    }

    /**
     * 获取校验规则
     * 
     * @param ruleName 规则名称
     * @return 校验规则
     */
    public ValidationRule getValidationRule(String ruleName) {
        return validationRules.get(ruleName);
    }

    /**
     * 获取校验规则集
     * 
     * @param ruleSetName 规则集名称
     * @return 校验规则集
     */
    public ValidationRuleSet getValidationRuleSet(String ruleSetName) {
        return validationRuleSets.get(ruleSetName);
    }

    /**
     * 获取所有校验规则
     * 
     * @return 校验规则列表
     */
    public List<ValidationRule> getAllValidationRules() {
        return new ArrayList<>(validationRules.values());
    }

    /**
     * 获取所有校验规则集
     * 
     * @return 校验规则集列表
     */
    public List<ValidationRuleSet> getAllValidationRuleSets() {
        return new ArrayList<>(validationRuleSets.values());
    }

    /**
     * 删除校验规则
     * 
     * @param ruleName 规则名称
     * @return 是否删除成功
     */
    public boolean removeValidationRule(String ruleName) {
        try {
            ValidationRule removed = validationRules.remove(ruleName);
            if (removed != null) {
                logger.info("校验规则删除成功: {}", ruleName);
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("删除校验规则失败: {}", ruleName, e);
            return false;
        }
    }

    /**
     * 删除校验规则集
     * 
     * @param ruleSetName 规则集名称
     * @return 是否删除成功
     */
    public boolean removeValidationRuleSet(String ruleSetName) {
        try {
            ValidationRuleSet removed = validationRuleSets.remove(ruleSetName);
            if (removed != null) {
                logger.info("校验规则集删除成功: {}", ruleSetName);
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("删除校验规则集失败: {}", ruleSetName, e);
            return false;
        }
    }

    /**
     * 获取校验统计信息
     * 
     * @return 统计信息
     */
    public ValidationStatistics getStatistics() {
        return new ValidationStatistics(
            totalValidations.get(),
            totalSuccessfulValidations.get(),
            totalFailedValidations.get(),
            totalRuleViolations.get(),
            validationRules.size(),
            validationRuleSets.size(),
            validationConfigs.size(),
            validationEnabled,
            strictMode,
            stopOnFirstError,
            maxValidationDepth,
            validationTimeout,
            System.currentTimeMillis()
        );
    }

    /**
     * 设置校验配置
     * 
     * @param enabled 是否启用校验
     * @param strictMode 严格模式
     * @param stopOnFirstError 遇到第一个错误时停止
     * @param maxValidationDepth 最大校验深度
     * @param validationTimeout 校验超时时间
     */
    public void setConfiguration(boolean enabled, boolean strictMode, boolean stopOnFirstError,
                               int maxValidationDepth, long validationTimeout) {
        this.validationEnabled = enabled;
        this.strictMode = strictMode;
        this.stopOnFirstError = stopOnFirstError;
        this.maxValidationDepth = maxValidationDepth;
        this.validationTimeout = validationTimeout;
        
        logger.info("数据校验配置已更新: 启用={}, 严格模式={}, 遇错停止={}, 最大深度={}, 超时时间={}ms", 
                   enabled, strictMode, stopOnFirstError, maxValidationDepth, validationTimeout);
    }

    /**
     * 解析数据
     */
    private Object parseData(String data) throws Exception {
        try {
            // 尝试解析为JSON
            return objectMapper.readValue(data, Object.class);
        } catch (Exception e) {
            // 如果不是JSON，返回原始字符串
            return data;
        }
    }

    /**
     * 执行校验
     */
    private boolean executeValidation(Object data, ValidationRuleSet ruleSet, 
                                    List<ValidationError> errors, int depth) {
        if (depth > maxValidationDepth) {
            errors.add(new ValidationError("MAX_DEPTH_EXCEEDED", "校验深度超过限制", null));
            return false;
        }
        
        boolean isValid = true;
        
        for (ValidationRule rule : ruleSet.getRules()) {
            try {
                ValidationResult ruleResult = executeRule(data, rule);
                if (!ruleResult.isValid()) {
                    errors.addAll(ruleResult.getErrors());
                    isValid = false;
                    
                    if (stopOnFirstError) {
                        break;
                    }
                }
            } catch (Exception e) {
                errors.add(new ValidationError("RULE_EXECUTION_ERROR", 
                    "规则执行异常: " + e.getMessage(), rule.getFieldPath()));
                isValid = false;
                
                if (stopOnFirstError) {
                    break;
                }
            }
        }
        
        return isValid;
    }

    /**
     * 执行单个规则
     */
    private ValidationResult executeRule(Object data, ValidationRule rule) {
        List<ValidationError> errors = new ArrayList<>();
        
        try {
            Object fieldValue = getFieldValue(data, rule.getFieldPath());
            
            switch (rule.getRuleType().toUpperCase()) {
                case "REQUIRED":
                    if (!validateRequired(fieldValue)) {
                        errors.add(new ValidationError("REQUIRED", "字段为必填项", rule.getFieldPath()));
                    }
                    break;
                case "NOT_NULL":
                    if (!validateNotNull(fieldValue)) {
                        errors.add(new ValidationError("NOT_NULL", "字段不能为空", rule.getFieldPath()));
                    }
                    break;
                case "NOT_EMPTY":
                    if (!validateNotEmpty(fieldValue)) {
                        errors.add(new ValidationError("NOT_EMPTY", "字段不能为空字符串", rule.getFieldPath()));
                    }
                    break;
                case "MIN_LENGTH":
                    if (!validateMinLength(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("MIN_LENGTH", "字段长度不足", rule.getFieldPath()));
                    }
                    break;
                case "MAX_LENGTH":
                    if (!validateMaxLength(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("MAX_LENGTH", "字段长度超限", rule.getFieldPath()));
                    }
                    break;
                case "MIN_VALUE":
                    if (!validateMinValue(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("MIN_VALUE", "字段值过小", rule.getFieldPath()));
                    }
                    break;
                case "MAX_VALUE":
                    if (!validateMaxValue(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("MAX_VALUE", "字段值过大", rule.getFieldPath()));
                    }
                    break;
                case "PATTERN":
                    if (!validatePattern(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("PATTERN", "字段格式不匹配", rule.getFieldPath()));
                    }
                    break;
                case "EMAIL":
                    if (!validateEmail(fieldValue)) {
                        errors.add(new ValidationError("EMAIL", "邮箱格式无效", rule.getFieldPath()));
                    }
                    break;
                case "PHONE":
                    if (!validatePhone(fieldValue)) {
                        errors.add(new ValidationError("PHONE", "手机号格式无效", rule.getFieldPath()));
                    }
                    break;
                case "URL":
                    if (!validateUrl(fieldValue)) {
                        errors.add(new ValidationError("URL", "URL格式无效", rule.getFieldPath()));
                    }
                    break;
                case "DATE":
                    if (!validateDate(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("DATE", "日期格式无效", rule.getFieldPath()));
                    }
                    break;
                case "IN_RANGE":
                    if (!validateInRange(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("IN_RANGE", "字段值不在范围内", rule.getFieldPath()));
                    }
                    break;
                case "IN_LIST":
                    if (!validateInList(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("IN_LIST", "字段值不在允许列表中", rule.getFieldPath()));
                    }
                    break;
                case "CUSTOM":
                    if (!validateCustom(fieldValue, rule.getConfig())) {
                        errors.add(new ValidationError("CUSTOM", "自定义校验失败", rule.getFieldPath()));
                    }
                    break;
                default:
                    errors.add(new ValidationError("UNKNOWN_RULE", "未知的校验规则类型: " + rule.getRuleType(), rule.getFieldPath()));
            }
        } catch (Exception e) {
            errors.add(new ValidationError("FIELD_ACCESS_ERROR", "字段访问异常: " + e.getMessage(), rule.getFieldPath()));
        }
        
        return new ValidationResult(errors.isEmpty(), errors.isEmpty() ? "VALID" : "INVALID", 
            errors.isEmpty() ? "校验通过" : "校验失败", errors);
    }

    /**
     * 获取字段值
     */
    private Object getFieldValue(Object data, String fieldPath) {
        if (fieldPath == null || fieldPath.isEmpty()) {
            return data;
        }
        
        if (data instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) data;
            return map.get(fieldPath);
        }
        
        return null;
    }

    /**
     * 校验必填
     */
    private boolean validateRequired(Object value) {
        return value != null;
    }

    /**
     * 校验非空
     */
    private boolean validateNotNull(Object value) {
        return value != null;
    }

    /**
     * 校验非空字符串
     */
    private boolean validateNotEmpty(Object value) {
        if (value == null) return false;
        if (value instanceof String) {
            return !((String) value).trim().isEmpty();
        }
        return true;
    }

    /**
     * 校验最小长度
     */
    private boolean validateMinLength(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof String) {
            int minLength = (Integer) config.get("minLength");
            return ((String) value).length() >= minLength;
        }
        return true;
    }

    /**
     * 校验最大长度
     */
    private boolean validateMaxLength(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof String) {
            int maxLength = (Integer) config.get("maxLength");
            return ((String) value).length() <= maxLength;
        }
        return true;
    }

    /**
     * 校验最小值
     */
    private boolean validateMinValue(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof Number) {
            double minValue = ((Number) config.get("minValue")).doubleValue();
            return ((Number) value).doubleValue() >= minValue;
        }
        return true;
    }

    /**
     * 校验最大值
     */
    private boolean validateMaxValue(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof Number) {
            double maxValue = ((Number) config.get("maxValue")).doubleValue();
            return ((Number) value).doubleValue() <= maxValue;
        }
        return true;
    }

    /**
     * 校验正则表达式
     */
    private boolean validatePattern(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof String) {
            String pattern = (String) config.get("pattern");
            return Pattern.matches(pattern, (String) value);
        }
        return true;
    }

    /**
     * 校验邮箱
     */
    private boolean validateEmail(Object value) {
        if (value == null) return true;
        if (value instanceof String) {
            String emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
            return Pattern.matches(emailPattern, (String) value);
        }
        return true;
    }

    /**
     * 校验手机号
     */
    private boolean validatePhone(Object value) {
        if (value == null) return true;
        if (value instanceof String) {
            String phonePattern = "^1[3-9]\\d{9}$";
            return Pattern.matches(phonePattern, (String) value);
        }
        return true;
    }

    /**
     * 校验URL
     */
    private boolean validateUrl(Object value) {
        if (value == null) return true;
        if (value instanceof String) {
            String urlPattern = "^(https?|ftp)://[^\\s/$.?#].[^\\s]*$";
            return Pattern.matches(urlPattern, (String) value);
        }
        return true;
    }

    /**
     * 校验日期
     */
    private boolean validateDate(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof String) {
            String datePattern = (String) config.getOrDefault("pattern", "yyyy-MM-dd");
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(datePattern);
                sdf.setLenient(false);
                sdf.parse((String) value);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    /**
     * 校验范围
     */
    private boolean validateInRange(Object value, Map<String, Object> config) {
        if (value == null) return true;
        if (value instanceof Number) {
            double minValue = ((Number) config.get("minValue")).doubleValue();
            double maxValue = ((Number) config.get("maxValue")).doubleValue();
            double numValue = ((Number) value).doubleValue();
            return numValue >= minValue && numValue <= maxValue;
        }
        return true;
    }

    /**
     * 校验列表
     */
    private boolean validateInList(Object value, Map<String, Object> config) {
        if (value == null) return true;
        @SuppressWarnings("unchecked")
        List<Object> allowedValues = (List<Object>) config.get("allowedValues");
        return allowedValues != null && allowedValues.contains(value);
    }

    /**
     * 自定义校验
     */
    private boolean validateCustom(Object value, Map<String, Object> config) {
        if (value == null) return true;
        // 这里可以实现自定义校验逻辑
        // 例如：调用外部服务、执行脚本等
        return true;
    }

    /**
     * 注册默认校验规则
     */
    private void registerDefaultValidationRules() {
        // 必填规则
        createValidationRule("required_name", "REQUIRED", "name", new HashMap<>());
        createValidationRule("required_email", "REQUIRED", "email", new HashMap<>());
        
        // 长度规则
        Map<String, Object> nameLengthConfig = new HashMap<>();
        nameLengthConfig.put("minLength", 2);
        nameLengthConfig.put("maxLength", 50);
        createValidationRule("name_length", "MIN_LENGTH", "name", nameLengthConfig);
        
        // 邮箱规则
        createValidationRule("email_format", "EMAIL", "email", new HashMap<>());
        
        // 手机号规则
        createValidationRule("phone_format", "PHONE", "phone", new HashMap<>());
        
        // 日期规则
        Map<String, Object> dateConfig = new HashMap<>();
        dateConfig.put("pattern", "yyyy-MM-dd");
        createValidationRule("date_format", "DATE", "date", dateConfig);
    }

    /**
     * 创建默认校验规则集
     */
    private void createDefaultValidationRuleSets() {
        List<String> defaultRules = Arrays.asList("required_name", "required_email", "name_length", "email_format");
        createValidationRuleSet("default", defaultRules, "默认校验规则集");
        
        List<String> userRules = Arrays.asList("required_name", "required_email", "name_length", "email_format", "phone_format");
        createValidationRuleSet("user", userRules, "用户数据校验规则集");
    }

    /**
     * 校验规则类
     */
    public static class ValidationRule {
        private final String ruleName;
        private final String ruleType;
        private final String fieldPath;
        private final Map<String, Object> config;

        public ValidationRule(String ruleName, String ruleType, String fieldPath, Map<String, Object> config) {
            this.ruleName = ruleName;
            this.ruleType = ruleType;
            this.fieldPath = fieldPath;
            this.config = config != null ? config : new HashMap<>();
        }

        // Getter方法
        public String getRuleName() { return ruleName; }
        public String getRuleType() { return ruleType; }
        public String getFieldPath() { return fieldPath; }
        public Map<String, Object> getConfig() { return config; }
    }

    /**
     * 校验规则集类
     */
    public static class ValidationRuleSet {
        private final String ruleSetName;
        private final List<ValidationRule> rules;
        private final String description;

        public ValidationRuleSet(String ruleSetName, List<ValidationRule> rules, String description) {
            this.ruleSetName = ruleSetName;
            this.rules = rules != null ? rules : new ArrayList<>();
            this.description = description;
        }

        // Getter方法
        public String getRuleSetName() { return ruleSetName; }
        public List<ValidationRule> getRules() { return rules; }
        public String getDescription() { return description; }
    }

    /**
     * 校验结果类
     */
    public static class ValidationResult {
        private final boolean valid;
        private final String status;
        private final String message;
        private final List<ValidationError> errors;

        public ValidationResult(boolean valid, String status, String message, List<ValidationError> errors) {
            this.valid = valid;
            this.status = status;
            this.message = message;
            this.errors = errors != null ? errors : new ArrayList<>();
        }

        // Getter方法
        public boolean isValid() { return valid; }
        public String getStatus() { return status; }
        public String getMessage() { return message; }
        public List<ValidationError> getErrors() { return errors; }
    }

    /**
     * 校验错误类
     */
    public static class ValidationError {
        private final String errorCode;
        private final String errorMessage;
        private final String fieldPath;

        public ValidationError(String errorCode, String errorMessage, String fieldPath) {
            this.errorCode = errorCode;
            this.errorMessage = errorMessage;
            this.fieldPath = fieldPath;
        }

        // Getter方法
        public String getErrorCode() { return errorCode; }
        public String getErrorMessage() { return errorMessage; }
        public String getFieldPath() { return fieldPath; }
    }

    /**
     * 校验配置类
     */
    public static class ValidationConfig {
        private final String key;
        private final String ruleSetName;
        private final boolean enabled;
        private final Map<String, Object> config;

        public ValidationConfig(String key, String ruleSetName, boolean enabled, Map<String, Object> config) {
            this.key = key;
            this.ruleSetName = ruleSetName;
            this.enabled = enabled;
            this.config = config != null ? config : new HashMap<>();
        }

        // Getter方法
        public String getKey() { return key; }
        public String getRuleSetName() { return ruleSetName; }
        public boolean isEnabled() { return enabled; }
        public Map<String, Object> getConfig() { return config; }
    }

    /**
     * 校验统计信息类
     */
    public static class ValidationStatistics {
        private final long totalValidations;
        private final long totalSuccessfulValidations;
        private final long totalFailedValidations;
        private final long totalRuleViolations;
        private final int activeRules;
        private final int activeRuleSets;
        private final int totalConfigs;
        private final boolean validationEnabled;
        private final boolean strictMode;
        private final boolean stopOnFirstError;
        private final int maxValidationDepth;
        private final long validationTimeout;
        private final long timestamp;

        public ValidationStatistics(long totalValidations, long totalSuccessfulValidations, long totalFailedValidations,
                                  long totalRuleViolations, int activeRules, int activeRuleSets, int totalConfigs,
                                  boolean validationEnabled, boolean strictMode, boolean stopOnFirstError,
                                  int maxValidationDepth, long validationTimeout, long timestamp) {
            this.totalValidations = totalValidations;
            this.totalSuccessfulValidations = totalSuccessfulValidations;
            this.totalFailedValidations = totalFailedValidations;
            this.totalRuleViolations = totalRuleViolations;
            this.activeRules = activeRules;
            this.activeRuleSets = activeRuleSets;
            this.totalConfigs = totalConfigs;
            this.validationEnabled = validationEnabled;
            this.strictMode = strictMode;
            this.stopOnFirstError = stopOnFirstError;
            this.maxValidationDepth = maxValidationDepth;
            this.validationTimeout = validationTimeout;
            this.timestamp = timestamp;
        }

        // Getter方法
        public long getTotalValidations() { return totalValidations; }
        public long getTotalSuccessfulValidations() { return totalSuccessfulValidations; }
        public long getTotalFailedValidations() { return totalFailedValidations; }
        public long getTotalRuleViolations() { return totalRuleViolations; }
        public int getActiveRules() { return activeRules; }
        public int getActiveRuleSets() { return activeRuleSets; }
        public int getTotalConfigs() { return totalConfigs; }
        public boolean isValidationEnabled() { return validationEnabled; }
        public boolean isStrictMode() { return strictMode; }
        public boolean isStopOnFirstError() { return stopOnFirstError; }
        public int getMaxValidationDepth() { return maxValidationDepth; }
        public long getValidationTimeout() { return validationTimeout; }
        public long getTimestamp() { return timestamp; }
        
        public double getSuccessRate() {
            return totalValidations > 0 ? (double) totalSuccessfulValidations / totalValidations : 0.0;
        }
        
        public double getFailureRate() {
            return totalValidations > 0 ? (double) totalFailedValidations / totalValidations : 0.0;
        }
    }
}
